/*
 * 阔地教育科技有限公司版权所有(codyy.com/codyy.cn)
 * Copyright (c) 2020, Codyy and/or its affiliates. All rights reserved.
 */

package com.codyy.lib_common.listener

import android.content.pm.ActivityInfo.*
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.os.Handler
import android.util.Log
import kotlin.math.atan2
import kotlin.math.roundToInt

/**
 * created by lijian on 2020/01/09
 * 参考:https://www.cnblogs.com/baiyi168/p/6184041.html
 */
class OrientationSensorListener(
    private val rotateHandler: Handler?
) : SensorEventListener {
    private var latestTime = 0L

    init {
        latestTime = System.currentTimeMillis()
    }

    override fun onAccuracyChanged(arg0: Sensor, arg1: Int) {

    }

    override fun onSensorChanged(event: SensorEvent) {
        if (System.currentTimeMillis() - latestTime > 1000L) {
            latestTime = System.currentTimeMillis()
            val values = event.values
            var orientation = ORIENTATION_UNKNOWN
            val x = -values[DATA_X]
            val y = -values[DATA_Y]
            val z = -values[DATA_Z]
            val magnitude = x * x + y * y
            // Don't trust the angle if the magnitude is small compared to the y value
            if (magnitude * 4 >= z * z) {
                val oneEightyOverPi = 57.29577957855f
                val angle = atan2((-y).toDouble(), x.toDouble()).toFloat() * oneEightyOverPi
                orientation = 90 - angle.roundToInt()
                // normalize to 0 - 359 range
                while (orientation >= 360) {
                    orientation -= 360
                }
                while (orientation < 0) {
                    orientation += 360
                }
            }
            val latestOrientation = when (orientation) {
                in 46..134 -> SCREEN_ORIENTATION_REVERSE_LANDSCAPE
                in 136..224 -> SCREEN_ORIENTATION_REVERSE_PORTRAIT
                in 226..314 -> SCREEN_ORIENTATION_LANDSCAPE
                in 316..359, in 1..44 -> SCREEN_ORIENTATION_PORTRAIT
                else -> ORIENTATION_UNKNOWN
            }
            rotateHandler?.run {
                obtainMessage(
                    SCREEN_ORIENTATION_MESSAGE,
                    latestOrientation,
                    0
                ).sendToTarget()
            }
        }


    }

    companion object {
        private const val DATA_X = 0
        private const val DATA_Y = 1
        private const val DATA_Z = 2
        const val ORIENTATION_UNKNOWN = -1
        const val SCREEN_ORIENTATION_MESSAGE = 888
    }
}
